package pers.gxm.command;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MyFrame extends JFrame implements ActionListener {
    public static void main(String[] args) {
        MyFrame frame = new MyFrame("命令模式");
    }
    private MacroCommand history = new MacroCommand();

    private DrawCanvas  canvas = new DrawCanvas(400,400,history);

    private JButton clearButton = new JButton("clear");
    private JButton red = new JButton("红笔");
    private JButton blue = new JButton("蓝笔");
    private JButton yellow = new JButton("黄笔");
    private JButton undo = new JButton("undo");

    public MyFrame(String title){
        super(title);
        this.addWindowListener(
                new WindowAdapter() {
                    @Override
                    public void windowClosing(WindowEvent e) {
                       System.exit(0);
                    }
                }
        );
        canvas.addMouseMotionListener(
                new MouseMotionAdapter() {
                    @Override
                    public void mouseDragged(MouseEvent e) {
                        DrawCommand drawCommand = new DrawCommand(canvas, e.getPoint());
                        history.append(drawCommand);
                        drawCommand.execute();
                    }
                }
        );

        clearButton.addActionListener(this);
        red.addActionListener(this);
        blue.addActionListener(this);
        yellow.addActionListener(this);
        undo.addActionListener(this);

        Box buttonBox = new Box(BoxLayout.X_AXIS);
        buttonBox.add(clearButton);
        buttonBox.add(red);
        buttonBox.add(blue);
        buttonBox.add(yellow);
        buttonBox.add(undo);
        
        Box mainBox = new Box(BoxLayout.Y_AXIS);
        mainBox.add(buttonBox);
        mainBox.add(canvas);
        
        getContentPane().add(mainBox);

        pack();
        setVisible(true);

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == clearButton){
            history.clear();
//            清空画布
            canvas.init();
            canvas.repaint();
        } else if (e.getSource() == undo) {
            history.undo();
            canvas.repaint();
//            canvas.paint();
        } else{
            SetColorCommand setColorCommand = null;
            if(e.getSource() == red){
                setColorCommand  = new SetColorCommand(canvas, Color.red);
            } else if (e.getSource() == blue) {
                setColorCommand = new SetColorCommand(canvas,Color.blue);
            }else if(e.getSource() == yellow){
                setColorCommand = new SetColorCommand(canvas,Color.yellow);
            }
            history.append(setColorCommand);
            setColorCommand.execute();
        }
    }
}
